/**
* @describe 音效
* @author 游金宇(KM)
* @date 2023-08-03 10:59:44
*/
import { AudioClip, AudioSource, error, _decorator } from 'cc';
import { CommonAudio } from './CommonAudio';

const { ccclass, menu } = _decorator;

/**
 * 注：用playOneShot播放的音乐效果，在播放期间暂时没办法即时关闭音乐
 */

/** 游戏音效 */
export class AudioEffect extends CommonAudio {
    private effects: Map<string, AudioClip> = new Map<string, AudioClip>();

    /**
     * 加载音效并播放
     * @param url           音效资源地址
     * @param callback      资源加载完成并开始播放回调
     */
    load(bundleName: string, url: string): Promise<AudioClip>
    load(url: string): Promise<AudioClip>
    load(arg1: string, arg2?: string) {
        return new Promise((resolve, reject) => {

            let bundleName: string | null = null;
            let url: string;

            if (arg2 !== undefined) {
                bundleName = arg1;
                url = arg2;
            } else {
                url = arg1;
            }

            const cb = (err: Error | null, data: AudioClip) => {
                if (err) {
                    return reject(err);
                }
                this.effects.set(url, data);
                this.playOneShot(data, this.volume);
                resolve(data)
            }

            bundleName
                ? this.cat.res.load(bundleName, url, AudioClip, cb)
                : this.cat.res.load(url, AudioClip, cb)


        })
    }

    /** 释放所有已使用过的音效资源 */
    release() {
        for (let key in this.effects) {
            this.cat.res.release(key);
        }
        this.effects.clear();
    }
}
